public class Solution34 {
    public int[] searchRange(int[] nums, int target) {
        if (nums.length == 0)
            return new int[]{-1, -1};
        int left = 0, right = nums.length - 1, mid;
        if (nums[left] > target || nums[right] < target) {
            return new int[]{-1, -1};
        }
        while (left <= right) {
            mid = (left + right) / 2;
            if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            } else {
                int start = search(nums, target, left, mid, true);
                int end = search(nums, target, mid, right, false);
                return new int[]{start, end};
            }
        }
        return new int[]{-1, -1};
    }

    //找到升序序列nums[left..right]第一个或最后一个target的值
    private int search(int[] nums, int target, int left, int right, boolean d) {
        if (d) {
            while (nums[left] < target) {
                int mid = (left + right) / 2;
                if (nums[mid] < target) {
                    left = mid + 1;
                } else {
                    return search(nums, target, left + 1, mid, true);
                }
            }
            return left;
        } else {
            while (nums[right] > target) {
                int mid = (left + right) / 2;
                if (nums[mid] > target) {
                    right = mid - 1;
                } else {
                    return search(nums, target, mid, right - 1, false);
                }
            }
            return right;
        }
    }
}
